<template>
	<a-card title="我的房源" :body-style="{ padding: '0' }">
		<!-- 预约状态筛选 -->
		<div class="select-container">
			房源状态：
			<a-select
				v-model:value="selectedStatus"
				placeholder="选择房源状态"
				style="width: 200px"
				@change="handleStatusChange"
			>
				<a-select-option value="all">全部</a-select-option>
				<a-select-option value="pending">待审核</a-select-option>
				<a-select-option value="approved">已通过</a-select-option>
				<a-select-option value="rejected">已拒绝</a-select-option>
				<a-select-option value="available">已上架</a-select-option>
				<a-select-option value="removed">已下架</a-select-option>
			</a-select>
		</div>
		<!-- 房源列表表格 -->
		<a-table
			:columns="columns"
			:data-source="houses"
			:pagination="false"
			:row-key="(record) => record.id"
			bordered
		>
			<template #bodyCell="{ column, record }">
				<!-- 房源图片：显示第一张 -->
				<template v-if="column.key === 'houseImage'">
					<img
						:src="record.imageUrls && record.imageUrls.length ? record.imageUrls[0] : ''"
						alt="房源图片"
						style="width: 110px; height: 86px; object-fit: cover"
					/>
				</template>
				<!-- 房源地址 -->
				<template v-else-if="column.key === 'address'">
					{{ record.address }}
				</template>
				<!-- 房源类型 -->
				<template v-else-if="column.key === 'houseType'">
					{{ record.houseType }}
				</template>
				<!-- 价格 -->
				<template v-else-if="column.key === 'price'"> {{ record.price }}</template>
				<!-- 状态 -->
				<template v-else-if="column.key === 'houseStatus'">
					{{ getStatus(record.houseStatus) }}
				</template>
				<!-- 备注 -->
				<template v-else-if="column.key === 'remarks'">
					{{ getStatus(record.remarks) }}
				</template>
				<!-- 操作列：详情、修改 -->
				<template v-else-if="column.key === 'action'">
					<a @click="goToDetails(record.id)">详情</a>
					<a style="margin-left: 1rem" @click="openEditModal(record)">修改</a>
					<template v-if="record.houseStatus === 'approved' || record.houseStatus === 'removed' ">
						<a style="margin-left: 1rem" @click="confirmUpdateStatus(record, '已上架')">上架</a>
					</template>
					<template v-else-if="record.houseStatus === 'available'">
						<a style="margin-left: 1rem" @click="confirmUpdateStatus(record, '已下架')">下架</a>
					</template>
				</template>
			</template>
		</a-table>

		<!-- 分页器 -->
		<a-pagination
			class="pagination"
			:current="pagination.current"
			:page-size="pagination.pageSize"
			:total="pagination.total"
			:page-size-options="['5', '10', '20', '50']"
			@change="handlePageChange"
			@showSizeChange="handlePageSizeChange"
			:show-total="(total, range) => `${range[0]}-${range[1]} 共 ${total} 条`"
			:locale="{ items_per_page: '条/页' }"
		></a-pagination>

		<!-- 修改房源信息 Modal（一比一复制“上传房源”表单结构） -->
		<a-modal
			v-model:visible="editModalVisible"
			title="修改房源"
			:width="1000"
			@ok="submitEdit"
			@cancel="cancelEdit"
			ok-text="确认修改"
			cancel-text="取消"
		>
			<a-form ref="editFormRef" :model="editForm" :rules="editRules" layout="vertical">
				<!-- 第一行：房源标题、小区、楼层 -->
				<a-row :gutter="24">
					<a-col :span="8">
						<a-form-item label="房源标题" name="title">
							<a-input v-model:value="editForm.title" placeholder="请输入房源标题" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="小区" name="community">
							<a-input v-model:value="editForm.community" placeholder="请输入小区名称" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="楼层" name="floor">
							<a-input-number v-model:value="editForm.floor" placeholder="请输入楼层" style="width: 100%" />
						</a-form-item>
					</a-col>
				</a-row>

				<!-- 第二行：地区、详细地址、地图定位按钮（可选） -->
				<a-row :gutter="24">
					<a-col :span="8">
						<a-form-item label="地区" required>
							<a-input v-model:value="editForm.region" disabled />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="详细地址" name="address">
							<a-input v-model:value="editForm.address" placeholder="请输入详细地址" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="房源定位">
							<a-button block class="ml-4" :disabled="!editForm.address" @click="openMapPicker">
								打开地图确定位置
							</a-button>
							<!-- 地图选择弹窗 -->
							<a-modal
								v-model:open="mapVisible"
								:destroyOnClose="false"
								title="选择位置"
								:confirmLoading="confirmLoading"
								@ok="onConfirmMap"
								cancelText="取消"
								okText="确认位置"
								width="40vw"
							>
								<div ref="mapRef" class="map-container"></div>
							</a-modal>
						</a-form-item>
					</a-col>
				</a-row>

				<!-- 第三行：房源描述 -->
				<a-row :gutter="24">
					<a-col :span="24">
						<a-form-item label="房源描述" name="description">
							<a-textarea v-model:value="editForm.description" placeholder="请输入房源描述" :rows="2" />
						</a-form-item>
					</a-col>
				</a-row>

				<!-- 第四行：房型（拆分成 room/hall/bathroom 三个下拉，组合到 houseType） -->
				<a-row :gutter="24">
					<a-col :span="24">
						<a-form-item label="房型（例如1房1厅1卫）" name="houseType">
							<a-row :gutter="8">
								<a-col :span="8">
									<a-select v-model:value="room" placeholder="请选择房间数量">
										<a-select-option value="1">1房</a-select-option>
										<a-select-option value="2">2房</a-select-option>
										<a-select-option value="3">3房</a-select-option>
									</a-select>
								</a-col>
								<a-col :span="8">
									<a-select v-model:value="hall" placeholder="请选择客厅数量">
										<a-select-option value="0">0厅</a-select-option>
										<a-select-option value="1">1厅</a-select-option>
										<a-select-option value="2">2厅</a-select-option>
										<a-select-option value="3">3厅</a-select-option>
									</a-select>
								</a-col>
								<a-col :span="8">
									<a-select v-model:value="bathroom" placeholder="请选择卫生间数量">
										<a-select-option value="1">1卫</a-select-option>
										<a-select-option value="2">2卫</a-select-option>
										<a-select-option value="3">3卫</a-select-option>
									</a-select>
								</a-col>
							</a-row>
						</a-form-item>
					</a-col>
				</a-row>

				<!-- 第五行：租金、租期、支付方式 -->
				<a-row :gutter="24">
					<a-col :span="6">
						<a-form-item label="面积" name="area">
							<a-input-number v-model:value="editForm.area" placeholder="请输入面积" style="width: 100%" />
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="租金" name="price">
							<a-input-number v-model:value="editForm.price" placeholder="请输入租金" style="width: 100%" />
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="租期" name="lease">
							<a-select v-model:value="editForm.lease" placeholder="请选择租期">
								<a-select-option value="一个月起">一个月起</a-select-option>
								<a-select-option value="三个月起">三个月起</a-select-option>
								<a-select-option value="半年起">半年起</a-select-option>
								<a-select-option value="一年起">一年起</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>

					<a-col :span="6">
						<a-form-item label="支付方式" name="payType">
							<a-input v-model:value="editForm.payType" placeholder="例如：押一付一" />
						</a-form-item>
					</a-col>
				</a-row>

				<!-- 第六行：配套设施、所属商圈、附近地铁站、步行时间 -->
				<a-row :gutter="24">
					<a-col :span="6">
						<a-form-item label="配套设施（多选）" name="facilities">
							<a-select
								mode="multiple"
								v-model:value="facilitiesSelected"
								placeholder="请选择配套设施"
								@change="handleFacilitiesChange"
							>
								<a-select-option v-for="item in facilitiesOptions" :key="item" :value="item">
									{{ item }}
								</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="所属商圈" name="businessArea">
							<a-select v-model:value="editForm.businessArea" placeholder="请选择商圈">
								<a-select-option v-for="area in businessAreas" :key="area" :value="area">
									{{ area }}
								</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="附近地铁站" name="subwayStation">
							<a-select v-model:value="editForm.subwayStation" placeholder="请选择地铁站">
								<a-select-option v-for="station in subwayStations" :key="station" :value="station">
									{{ station }}
								</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="步行到地铁站时间（分钟）" name="traffic">
							<a-input-number v-model:value="editForm.traffic" placeholder="请输入步行时间" style="width: 100%" />
						</a-form-item>
					</a-col>
				</a-row>

				<!-- 第七行：图片上传 -->
				<a-row :gutter="24">
					<a-col :span="24">
						<a-form-item label="房源图片" name="imageUrls" required>
							<a-upload
								:fileList="fileList"
								:beforeUpload="beforeUpload"
								:onRemove="handleRemove"
								list-type="picture-card"
								multiple
								:isImageUrl="() => true"
								:maxCount="5"
							>
								<div>
									<PlusOutlined />
									<div style="margin-top: 8px">选择图片</div>
								</div>
							</a-upload>
						</a-form-item>
					</a-col>
				</a-row>

				<a-row :gutter="24">
					<a-col :span="24">
						<a-form-item label="产权证明（仅支持PDF文件）" name="titleDeed">
							<a-upload
								:beforeUpload="beforeUploadTitleDeed"
								:onRemove="handleRemoveTitleDeed"
								list-type="text"
								:maxCount="1"
								:accept="'.pdf'"
							>
								<a-button>
									<UploadOutlined />
									更换产权证明
								</a-button>
								<a-button type="primary" v-if="editForm.titleDeed" @click="previewTitleDeed" style="margin-left: 20px"
								>预览当前产权证明
								</a-button>
							</a-upload>
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</a-modal>
	</a-card>
</template>

<script setup>
	import { onMounted, ref, reactive, watch, nextTick } from 'vue';
	import { message, Modal } from 'ant-design-vue';
	import landlordApi from '@/api/landlordApi';
	import AMapLoader from '@amap/amap-jsapi-loader';

	// ===================== 高德地图关键配置 =====================
	// 1. 读取环境变量
	const AMAP_KEY = import.meta.env.VITE_AMAP_KEY;
	const SECURITY_KEY = import.meta.env.VITE_SECURITY_KEY;

	// 2. 如果开启了安全密钥，需要配置 SecurityJsCode
	window._AMapSecurityConfig = {
		securityJsCode: import.meta.env.VITE_SECURITY_JSCODE
	};

	// 3. 一个示例的存储对象（若你需要在地图选点后存储结果，可使用）
	const result = reactive({
		location: '',
		address: '',
		lngAndLat: ''
	});

	// ===================== 列表/分页相关 =====================
	const houses = ref([]);
	const pagination = reactive({
		current: 1,
		pageSize: 10,
		total: 0
	});

	const columns = [
		{ title: '房源图片', dataIndex: 'houseImage', key: 'houseImage', width: 120 },
		{ title: '房源地址', dataIndex: 'address', key: 'address' },
		{ title: '房源类型', dataIndex: 'houseType', key: 'houseType', width: 100 },
		{ title: '价格', dataIndex: 'price', key: 'price', width: 50 },
		{ title: '状态', dataIndex: 'houseStatus', key: 'houseStatus', width: 80 },
		{ title: '备注', dataIndex: 'remarks', key: 'remarks', width: 150 },
		{ title: '操作', dataIndex: 'action', key: 'action', width: 150 }
	];

	// 加载“我的房源”
	const loadHouses = () => {
		landlordApi
			.getMyHouse(pagination.current, pagination.pageSize, selectedStatus.value)
			.then((res) => {
				if (res.code === 200) {
					houses.value = res.data.houses;
					pagination.total = res.data.total;
				} else {
					message.error(res.message || '查询失败');
				}
			})
			.catch(() => {
				message.error('获取房源数据失败');
			});
	};

	const confirmUpdateStatus = (record, changeStatus) => {
		Modal.confirm({
			title: `确认${changeStatus === '已上架' ? '上架' : '下架'}该房源吗？`,
			okText: '确认',
			cancelText: '取消',
			onOk() {
				const newStatus = changeStatus === '已上架' ? 'available' : 'removed';

				landlordApi
					.updateHouseStatus({ houseId: record.id, newStatus })
					.then((res) => {
						if (res.code === 200) {
							message.success(`${changeStatus === '已上架' ? '上架' : '下架'}成功`);
							// 刷新房源列表
							loadHouses();
						} else {
							message.error(res.message || '操作失败');
						}
					})
					.catch(() => {
						message.error('操作失败，请重试');
					});
			}
		});
	};

	const handlePageChange = (page) => {
		pagination.current = page;
		loadHouses();
	};
	const handlePageSizeChange = (current, size) => {
		pagination.pageSize = size;
		pagination.current = 1;
		loadHouses();
	};
	const selectedStatus = ref('all');
	const handleStatusChange = (value) => {
		selectedStatus.value = value;
		pagination.current = 1;
		loadHouses();
	};


	const getStatus = (status) => {
		const statusMap = {
			pending: '待审核',
			approved: '已通过',
			rejected: '已拒绝',
			available: '已上架',
			removed: '已下架'
		};
		return statusMap[status] || status;
	};

	const goToDetails = (houseId) => {
		window.open(`/house-details/${houseId}`, '_blank');
	};

	// ===================== 修改Modal：与上传房源一致 =====================
	const editModalVisible = ref(false);
	const editFormRef = ref(null);

	const editForm = ref({
		id: null,
		title: '',
		community: '',
		floor: null,
		region: '广东省广州市花都区',
		area: '',
		address: '',
		description: '',
		houseType: '',
		price: null,
		lease: '',
		payType: '',
		facilities: '',
		businessArea: '',
		subwayStation: '',
		traffic: null,
		longitude: '',
		latitude: '',
		imageUrls: [],
		titleDeed: '', // 新增产权证明URL字段
		fileType: '' // 新增产权证明文件类型
	});

	// 校验规则（可根据上传页面规则做相应调整）
	const editRules = {
		title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
		community: [{ required: true, message: '小区不能为空', trigger: 'blur' }],
		floor: [{ required: true, message: '楼层不能为空', trigger: 'blur' }],
		address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
		description: [{ required: true, message: '房源描述不能为空', trigger: 'blur' }],
		houseType: [{ required: true, message: '房型不能为空', trigger: 'blur' }],
		price: [{ required: true, message: '租金不能为空', trigger: 'blur' }],
		area: [{ required: true, message: '面积不能为空', trigger: 'blur' }],
		lease: [{ required: true, message: '租期不能为空', trigger: 'blur' }],
		payType: [{ required: true, message: '支付方式不能为空', trigger: 'blur' }],
		facilities: [{ required: true, message: '请选择配套设施', trigger: 'change' }],
		businessArea: [{ required: true, message: '请选择商圈', trigger: 'blur' }],
		subwayStation: [{ required: true, message: '请选择地铁站', trigger: 'blur' }],
		traffic: [{ required: true, message: '请输入步行时间', trigger: 'blur' }],
		titleDeed: [{ required: true, message: '请上传产权证明', trigger: 'blur' }],
	};

	// ======= 房型三字段（room、hall、bathroom） =======
	const room = ref(null);
	const hall = ref(null);
	const bathroom = ref(null);

	// 当 room/hall/bathroom 变化时，更新 editForm.houseType
	watch([room, hall, bathroom], ([r, h, b]) => {
		if (r && h && b) {
			editForm.value.houseType = `${r}房${h}厅${b}卫`;
		} else {
			editForm.value.houseType = '';
		}
	});

	const parseHouseType = (houseType) => {
		const match = houseType.match(/(\d+)房(\d+)厅(\d+)卫/);
		if (match) {
			room.value = match[1];
			hall.value = match[2];
			bathroom.value = match[3];
		} else {
			room.value = null;
			hall.value = null;
			bathroom.value = null;
		}
	};

	// ======= 配套设施多选 =======
	const facilitiesSelected = ref([]);
	const facilitiesOptions = ['床', '厨房', '热水器', '空调', '网络', '电视', '冰箱', '洗衣机', '衣柜', '电梯'];
	const handleFacilitiesChange = (value) => {
		facilitiesSelected.value = value;
		editForm.value.facilities = value.join(',');
	};
	const parseFacilities = (str) => {
		if (!str) return [];
		return str.split(',').filter(Boolean);
	};

	// ======= 商圈、地铁站示例数据 =======
	const businessAreas = [
		'花都广场/区政府',
		'来又来/大润发',
		'白云国际机场',
		'新世纪广场',
		'花山',
		'狮岭',
		'雅瑶',
		'融创茂',
		'雅房乐锦城/保利花城',
		'骏壹万邦',
		'建设北路'
	];
	const subwayStations = [
		'高增',
		'清塘',
		'清布',
		'莲塘',
		'马鞍山公园',
		'花都广场',
		'花果山公园',
		'花城路',
		'广州北站',
		'花都汽车城',
		'飞鹅岭'
	];

	// ======= 图片上传相关 =======
	const fileList = ref([]);

	// 使用箭头函数写法
	const beforeUpload = (file) => {
		const formData = new FormData();
		formData.append('file', file);
		return landlordApi
			.uploadHouseImg(formData)
			.then((response) => {
				if (response.code === 200) {
					const imageUrl = response.data[0];
					editForm.value.imageUrls.push(imageUrl);
					fileList.value.push({
						uid: file.uid,
						name: file.name,
						status: 'done',
						url: imageUrl
					});
					message.success('图片上传成功');
				} else {
					message.error(response.message || '图片上传失败');
				}
			})
			.catch(() => {
				message.error('图片上传失败，请重试');
			})
			.finally(() => false); // 阻止默认上传
	};

	const handleRemove = (file) => {
		fileList.value = fileList.value.filter((f) => f.uid !== file.uid);
		editForm.value.imageUrls = editForm.value.imageUrls.filter((url) => url !== file.url);
	};

	// ======= 地图定位相关 =======
	const mapVisible = ref(false);
	const mapRef = ref(null);
	const mapIns = ref(null);
	const mapMarker = ref(null);
	const confirmLoading = ref(false);

	const openMapPicker = () => {
		mapVisible.value = true;
		nextTick(() => {
			const fullAddress = getFullAddress();
			if (mapIns.value) {
				updateMapCenter(fullAddress);
			} else {
				renderMap(fullAddress);
			}
		});
	};

	const getFullAddress = () => {
		return editForm.value.region + editForm.value.address;
	};

	// 载入高德地图
	const loadAMap = () => {
		return AMapLoader.load({
			key: AMAP_KEY,
			version: '2.0',
			securityJsCode: SECURITY_KEY,
			plugins: ['AMap.Geocoder', 'AMap.Marker']
		});
	};

	const updateMapCenter = (address) => {
		loadAMap()
			.then((AMap) => {
				const geocoder = new AMap.Geocoder({
					city: '020',
					radius: 500
				});
				geocoder.getLocation(address, (status, result) => {
					if (status === 'complete' && result.geocodes.length) {
						const { lng, lat } = result.geocodes[0].location;
						if (mapIns.value) {
							mapIns.value.setCenter([lng, lat]);
							console.log(`地图中心点的地址为：${address}，经纬度 ${lng},${lat}`);
							if (mapMarker.value) {
								mapMarker.value.setPosition([lng, lat]);
							} else {
								mapMarker.value = new AMap.Marker({
									position: [lng, lat],
									map: mapIns.value
								});
							}
							editForm.value.latitude = lat;
							editForm.value.longitude = lng;
						}
					} else {
						console.error('地址解析失败:', address);
					}
				});
			})
			.catch((error) => {
				console.error('加载AMap失败', error);
			});
	};

	const renderMap = (address) => {
		AMapLoader.load({
			key: AMAP_KEY,
			version: '2.0',
			plugins: ['AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Marker', 'AMap.Geocoder']
		})
			.then((AMap) => {
				const resolvedAddress = address || '广东省花都区花都广场';
				const geocoder = new AMap.Geocoder({
					city: '020',
					radius: 500
				});
				geocoder.getLocation(resolvedAddress, (status, result) => {
					if (status === 'complete' && result.geocodes.length) {
						const { lng, lat } = result.geocodes[0].location;
						console.log(`地图中心点的地址为：${address}，经纬度 ${lng},${lat}`);
						mapIns.value = new AMap.Map(mapRef.value, {
							zoom: 19,
							center: [lng, lat],
							resizeEnable: true
						});
						mapMarker.value = new AMap.Marker({
							position: [lng, lat],
							map: mapIns.value
						});
						editForm.value.latitude = lat;
						editForm.value.longitude = lng;
					} else {
						console.error('地址解析失败，使用默认地图中心');
						mapIns.value = new AMap.Map(mapRef.value, {
							zoom: 19,
							center: [113.122717, 23.028762],
							resizeEnable: true
						});
					}
					mapIns.value.on('click', (e) => {
						const { lng, lat } = e.lnglat;
						mapMarker.value.setPosition([lng, lat]);
						editForm.value.latitude = lat;
						editForm.value.longitude = lng;
						console.log(`用户点击了地图：经度 ${lng}, 纬度 ${lat}`);
					});
					mapIns.value.on('complete', () => {});
				});
			})
			.catch((e) => {
				console.error('地图加载失败', e);
			});
	};

	const onConfirmMap = () => {
		const { lng, lat } = mapIns.value.getCenter();
		result.lngAndLat = `${lng}, ${lat}`;
		editForm.value.latitude = lat;
		editForm.value.longitude = lng;
		mapVisible.value = false;
	};

	// ===================== 点击“修改”时，打开Modal，回显数据 =====================
	const openEditModal = (record) => {
		console.log('房源数据:', record);
		editModalVisible.value = true;

		// 1) 先清空表单
		resetEditForm();
		// 2) 将 record 的数据复制到 editForm.value
		Object.assign(editForm.value, record);
		if (!editForm.value.region) {
			editForm.value.region = '广东省广州市花都区';
		}
		// 3) 解析 houseType -> room/hall/bathroom
		parseHouseType(editForm.value.houseType || '');
		// 4) 解析配套设施 -> 数组
		facilitiesSelected.value = parseFacilities(editForm.value.facilities);
		// 5) 构建 fileList
		fileList.value = [];
		if (editForm.value.imageUrls && editForm.value.imageUrls.length) {
			editForm.value.imageUrls.forEach((url, index) => {
				fileList.value.push({
					uid: `${Date.now()}-${index}`,
					name: `image-${index}`,
					status: 'done',
					url
				});
			});
		}
	};

	const submitEdit = () => {
		editFormRef.value
			.validate()
			.then(() => {
				Modal.confirm({
					title: '确认修改房源信息吗？',
					okText: '确认',
					cancelText: '取消',
					onOk() {
						const data = editForm.value;
						console.log('编辑数据:' + data);
						landlordApi
							.updateHouse(data)
							.then((res) => {
								if (res.code === 200) {
									message.success('修改成功');
									editModalVisible.value = false;
									loadHouses();
								} else {
									message.error(res.message || '修改失败');
								}
							})
							.catch(() => {
								message.error('修改房源失败');
							});
					}
				});
			})
			.catch((err) => {
				console.error(err);
				message.error('请检查表单信息是否填写完整或正确');
			});
	};

	const cancelEdit = () => {
		editModalVisible.value = false;
	};

	const resetEditForm = () => {
		Object.assign(editForm.value, {
			id: null,
			title: '',
			community: '',
			floor: null,
			region: '广东省广州市花都区',
			address: '',
			description: '',
			houseType: '',
			price: null,
			lease: '',
			payType: '',
			facilities: '',
			businessArea: '',
			subwayStation: '',
			traffic: null,
			longitude: '',
			latitude: '',
			imageUrls: []
		});
		room.value = null;
		hall.value = null;
		bathroom.value = null;
		facilitiesSelected.value = [];
		fileList.value = [];
	};

	// 新增上传逻辑
	const beforeUploadTitleDeed = (file) => {
		const fileType = file.type;

		if (fileType !== 'application/pdf') {
			message.error('仅支持上传 PDF 文件');
			return false;  // 阻止非 PDF 文件上传
		}

		const formData = new FormData();
		formData.append('file', file);

		// 上传文件
		landlordApi.uploadTitleDeed(formData)
			.then((response) => {
				editForm.value.titleDeed = response.data[0].url;
				editForm.value.fileType = response.data[0].fileType;
				message.success('产权证明上传成功');
			})
			.catch((error) => {
				message.error('上传失败');
			});

		return false;  // 阻止默认上传行为
	};


	// 新增删除逻辑
	const handleRemoveTitleDeed = () => {
		editForm.value.titleDeed = '';
	};

	// 新增预览逻辑
	const previewTitleDeed = () => {
		window.open(editForm.value.titleDeed, '_blank'); // 打开预览页面
	};
	// 初始化时加载
	onMounted(() => {
		loadHouses();
	});
</script>

<style scoped>
	.pagination {
		margin: 1rem 0;
		text-align: right;
	}

	.map-container {
		height: 50vh;
	}

	.ml-4 {
		margin-left: 0;
		color: #0056b3;
		font-weight: bold;
		border: 1px dashed #0056b3;
	}

	.select-container {
		align-items: center;
		margin-bottom: 1rem;
		display: flex;
		text-align: center;
		justify-content: flex-end;
		font-size: 15px;
	}
</style>
